package inabit.compiler.lexical.automaton;

/**Executes an automaton by changing the states through the transitions
 * and halting when cannot perform a transition*/
/**@author Rafael Rocha*/
public class AutomataRunner {
	//the automaton to run
	private Automata automaton;
	//the current state on the automaton
	private String currentState;
	//the recognized word so far in the automaton
	private String recognizedWord;
	
	public AutomataRunner(Automata automaton) {
		this.automaton = automaton;
		init();
	}
	
	/**initialize the automaton runner setting the current state to the initial state
	 * of the automaton*/
	public void init() {
		this.currentState = automaton.getInitialState();
		this.recognizedWord = "";
	}
	
	/**tries to perform a transition on automaton, return <i>false</i> if there's no
	 * transition or <i>false</i> otherwise*/
	public boolean transition(char c) {
		String nextState = automaton.getTargetState(currentState, c);
		if(nextState != null) {
			currentState = nextState;
			recognizedWord += c;
			if(currentState.equals(automaton.getInitialState())) {
				recognizedWord = "";
			}
			return true;
		}
		return false;
	}
	/**Returns the current state of the automaton*/
	public String getCurrentState() {
		return this.currentState;
	}
	/**Returns the recognized word so far in the automaton*/
	public String getRecognizedWord() {
		return recognizedWord;
	}
}
